package com.cscp.javastudy.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketSaleDemo2 {

    public static void main(String[] args) {

        Ticket2 ticket = new Ticket2();
        // (参数) -> {代码...}
        new Thread(() -> {for (int i = 1; i < 60; i++) ticket.sale();}, "A").start();
        new Thread(() -> {for (int i = 1; i < 60; i++) ticket.sale();}, "B").start();
        new Thread(() -> {for (int i = 1; i < 60; i++) ticket.sale();}, "C").start();
    }

}


/**
 * 资源类
 */
class Ticket2 {
    // 属性
    private int number = 30;

    // 1 New一个锁,默认是非公平锁
    Lock lock = new ReentrantLock();//传入参数的话就是公平锁
    // 方法
    public void sale(){

        // 2 加锁
        lock.lock();

        try {
            // 业务代码
            if (number>0){
                System.out.println(Thread.currentThread().getName()+" 卖出了 " + (number--) + " 票，剩余：" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 3 解锁
            lock.unlock();
        }
    }
}
